//
//  JQFYHomeViewController.m
//  JQFY
//
//  Created by apple on 2017/8/6.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYHomeViewController.h"
#import "JQFYScrollView.h"
#import "JQFYRhythmView.h"
#import "JQFYPlayViewController.h"
#import "JQFYBaseNavigationController.h"
#import "JQFYMusicChartCell.h"
#import "JQFYMusicListCell.h"
#import "CALayer+Animation.h"
#import "JQFYPlayListManger.h"
#import "JQFYHomeBannerModel.h"
#import "JQFYBannerViewController.h"
#import "JQFYHomeRecommendMusic.h"
#import "JQFYMusicGenreCell.h"
#import "JQFYHomeFooter.h"
#import "JQFYSectionHeader.h"
#import "JQFYMusicGenreViewController.h"
#import "JQFYSpecialDetailsViewController.h"
#import "JQFYRecommendViewController.h"
#import "JQFYHotMusicianViewController.h"
#import "JQFYGratefulMusicianCell.h"

@interface JQFYHomeViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>

@property(nonatomic, strong) JQFYRhythmView *rhythmView;                 /// 律动条
@property (nonatomic,strong) SDCycleScrollView *scr;                       /// 轮播器
@property (nonatomic,strong) NSArray *sectionHeaderViewTitleArray;      /// 组头文字
@property (nonatomic,strong) NSArray *sectionHeaderViewTitleIconArray;  /// 组头图片
@property (nonatomic,weak)   UITableView *homeList;
@property (nonatomic,strong) NSArray <JQFYHomeBannerModel *>*cycleImages;
@property (nonatomic,strong) ZJAnimationPopView *alert;
@property (nonatomic,assign) NSUInteger refreshNum;
@property (nonatomic,strong) MJRefreshAutoNormalFooter *footer;
@property (nonatomic,strong) NSArray *recommendMusics;
@property (nonatomic,assign) BOOL isSelect;
@property (nonatomic,strong) NSMutableArray *images;

@end
static NSString *musicGenreCell = @"musicGenreCell";
static NSString *MusicChart = @"MusicChart";
static NSString *MusicList = @"MusicList";
static NSString *HotMusician = @"HotMusician";
static NSString *BaseHead = @"BaseHead";
static NSString *SectionHeaderView = @"SectionHeaderView";

@implementation JQFYHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.refreshNum = 6;
    self.sectionHeaderViewTitleArray = @[@"电子音乐流派",@"热门专辑",@"每日推荐",@"最受欢迎音乐人"];
//    [self loadData];
    [self setupUI];
    // 轮播器
    [self setupScr];
    [self setupRefreshControl];
    [self setNotification];
    
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (__Player__.playingSong == nil) {
        return;
    }
    if (__Player__.playIndexPath) {
        if (self.homeList) {
            
            if (__Player__.playIndexPath.section == 0) {
                self.isSelect = YES;
                NSInteger index = [__Player__.recommendMusics indexOfObject:__Player__.playingSong];
//                [self collectionView:self.homeList didSelectItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
            }
        }
    }
}

#pragma mark - 加载数据 -
- (void)loadData{
    
    __weak typeof(self) weakSelf = self;
    [[[JQFYHomeBannerModel alloc] init] getCycleImage:^(NSArray *cycleImages) {
        NSMutableArray *urlImages = [NSMutableArray new];
        for (JQFYHomeBannerModel *model in cycleImages) {
            [urlImages addObject:model.cover];
        }
        weakSelf.cycleImages = cycleImages;
        weakSelf.scr.imageURLStringsGroup = urlImages;
        [MBProgressHUD showWithMessage:@"加载成功"];
    } file:^{
        [MBProgressHUD showWithMessage:@"加载失败"];
    }];
    
    [_PlaylistMgr getHomeRecommendMusic:^(NSArray *musics) {
        weakSelf.recommendMusics = musics;
    } file:nil];
    
    [_PlaylistMgr getMusicData:^{
        JQFYPlayList *list = _PlaylistMgr.allPlaylists.firstObject;
        __Player__.songs = list.allSongs;
    } failure:nil];
}
#pragma mark - 通知 -
- (void)setNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(animationing:) name:JQFYMusicPlayerStatusDidChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerPlayingSongDidChangedNotification:) name:JQFYMusicPlayerPlayingSongDidChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickMore:) name:@"clickMore" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(specialDetails:) name:@"SpecialDetails" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recommendMusicPlay:) name:@"recommendMusicPlay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hotMusician:) name:@"HotMusician" object:nil];
}

#pragma mark - 播放歌曲发生改变时候的通知 -
- (void)musicPlayerPlayingSongDidChangedNotification:(NSNotification *)noti
{
    JQFYSong *playingSong = noti.userInfo[kMusicPlayerPlayingSong];
    if (__Player__.currentModel) {
        __Player__.currentModel.play = !__Player__.currentModel.play;
    }
    if (__Player__.currentEffView) {
        __Player__.currentEffView.alpha = 0.7;
    }
    playingSong.play = !playingSong.play;
    __Player__.currentModel = playingSong;
    [self.homeList reloadData];

}

#pragma mark - 点击更多跳转控制器 -
- (void)clickMore:(NSNotification *)noti
{
    NSInteger index = [noti.object integerValue];
    if (index == 0) {
        JQFYMusicGenreViewController *musicGenre = [JQFYMusicGenreViewController new];
#warning 需要具体设置数据
        musicGenre.musicGenries = self.recommendMusics;
        [self.navigationController pushViewController:musicGenre animated:YES];   
    }
}

#pragma mark - 跳转专辑详情 -
- (void)specialDetails:(NSNotification *)noti
{
    NSIndexPath *indexPath = noti.object;
#warning 需要具体设置数据
    JQFYSpecialDetailsViewController *special = [JQFYSpecialDetailsViewController new];
    special.dataArray = self.recommendMusics;
    [self.navigationController pushViewController:special animated:YES];
    
}

#pragma mark - 跳转每日推荐 -
- (void)recommendMusicPlay:(NSNotification *)noti
{
    [self presentViewController:[JQFYPlayViewController new] animated:YES completion:nil];
}

#pragma mark - 跳转热门音乐人界面 -
- (void)hotMusician:(NSNotification *)noti
{
    NSIndexPath *indexPath = noti.object;
#warning 需要具体设置数据
    JQFYHotMusicianViewController *musician = [JQFYHotMusicianViewController new];
    [self.navigationController pushViewController:musician animated:YES];
    
}
#pragma mark - 下拉刷新 -
- (void)setupRefreshControl
{
    //下拉刷新
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    [header setImages:self.images forState:MJRefreshStateIdle];
    [header setImages:self.images forState:MJRefreshStatePulling];
    [header setImages:self.images forState:MJRefreshStateRefreshing];
    self.homeList.mj_header = header;
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    [self.homeList.mj_header beginRefreshing];
}

- (void)refresh
{
    [self.homeList.mj_header beginRefreshing];
    [self loadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.homeList.mj_header endRefreshing];
        [self.homeList reloadData];
    });
    
}
#pragma mark - 音乐的播放状态控制律动条是否动画 -
- (void)animationing:(NSNotification *)noti
{
    JQFYMusicPlayerStatus status = [noti.userInfo[kMusicPlayerStatus] integerValue];
    if (status == JQFYMusicPlayerStatusPlaying) {
        
        if (self.rhythmView.animation) {
            return;
        }
        [self.rhythmView beginAnimation];
        
    } else {
       
        [self.rhythmView stopAnimation];
    }
}
#pragma mark - 界面布局 -
-(void)setupUI{

    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    // Logo
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MUSIC"]];
    // 律动条
    self.rhythmView = [[JQFYRhythmView alloc]initWithFrame:CGRectMake(DH_Screen_Width - 40 *SCAL, 12 *SCAL, 20 *SCAL, 20 *SCAL)];

    UIView *tempView = [[UIView alloc] init];
    tempView.backgroundColor = [UIColor clearColor];
    tempView.frame = CGRectMake(0, 0, 35 *SCAL, 35 *SCAL);
    tempView.center = self.rhythmView.center;
    [tempView addSubview:self.rhythmView];
    
    [self.navigationController.navigationBar addSubview:self.rhythmView];
    [self.navigationController.navigationBar addSubview:tempView];

    //添加手势
    UITapGestureRecognizer *rhythmGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRhythmView)];
    [tempView addGestureRecognizer:rhythmGesture];
    
    //UITableView
    UITableView *homeList = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:homeList];
    [homeList mas_makeConstraints:^(MASConstraintMaker *make) {
         make.edges.mas_equalTo(self.view);
    }];
    [homeList registerClass:[JQFYMusicListCell class] forCellReuseIdentifier:MusicList];
    [homeList registerClass:[JQFYMusicGenreCell class] forCellReuseIdentifier:musicGenreCell];
    [homeList registerClass:[JQFYMusicChartCell class] forCellReuseIdentifier:MusicChart];
    [homeList registerClass:[JQFYGratefulMusicianCell class] forCellReuseIdentifier:HotMusician];
    homeList.tableFooterView = [[JQFYHomeFooter alloc] initWithFrame:CGRectMake(0, 0, DH_Screen_Width, 80 *SCAL)];
    homeList.dataSource = self;
    homeList.delegate = self;
    homeList.sectionHeaderHeight = 64 *SCAL;
    homeList.separatorStyle = UITableViewCellSeparatorStyleNone;
    homeList.backgroundColor = [UIColor clearColor];
    homeList.showsVerticalScrollIndicator = NO;
    self.homeList = homeList;
    UIImageView *top = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header"]];
    [self.view addSubview:top];
    [top mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.equalTo(self.view);
    }];
   
}

#pragma mark - UICollectionViewDataSource -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 1 || section == 3) {
        return 1;
    }
    
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        JQFYMusicGenreCell * cell = [tableView dequeueReusableCellWithIdentifier:musicGenreCell forIndexPath:indexPath];
        if (self.recommendMusics.count) {
            
            cell.songInfo = self.recommendMusics;
        }
        return cell;
    }
    if (indexPath.section == 1) {
        JQFYMusicChartCell *cell = [tableView dequeueReusableCellWithIdentifier:MusicChart forIndexPath:indexPath];
        if (self.recommendMusics.count) {
            cell.songs = self.recommendMusics;
        }
        return cell;
    }
    
    if (indexPath.section == 2) {
        
        JQFYMusicListCell *cell = [tableView dequeueReusableCellWithIdentifier:MusicList forIndexPath:indexPath];
        cell.model = self.recommendMusics[indexPath.row];
        return cell;
        
    }
    JQFYGratefulMusicianCell *cell = [tableView dequeueReusableCellWithIdentifier:HotMusician forIndexPath:indexPath];
    if (self.recommendMusics.count) {
        cell.songs = self.recommendMusics;
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    JQFYSectionHeader *header = [JQFYSectionHeader new];
    header.title = self.sectionHeaderViewTitleArray[section];
    header.index = section;
    return header;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 2) {
        JQFYRecommendViewController *recommend = [JQFYRecommendViewController new];
        [self.navigationController pushViewController:recommend animated:YES];
    }
    return;
    
    JQFYMusicChartCell *cell = (JQFYMusicChartCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    if (!self.isSelect) {
      
        if (__Player__.isPlaying) {
            [__Player__ pause];
        }
        
    } else {
        self.isSelect = NO;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 129 *0.5*SCAL;
    }
    if (indexPath.section == 1) {
        return 395 *0.5*SCAL;
    }
    if (indexPath.section == 2) {
        return 54 *SCAL;
    }
    return 338 *0.5 *SCAL;
}
#pragma mark - 轮播器 -
-(void)setupScr{
    
    self.scr = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(-12 *SCAL, -206 *SCAL, DH_Screen_Width, 208 *SCAL) delegate:self placeholderImage:[UIImage imageNamed:@"Electronicmusiclabel（合并）（合并）"]];
    self.scr.currentPageDotImage = [UIImage imageNamed:@"#1"];
    self.scr.pageDotImage = [UIImage imageNamed:@"#2"];
    self.scr.autoScrollTimeInterval = 4;
    self.scr.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    
    __weak typeof(self) weakSelf = self;
    self.scr.clickItemOperationBlock = ^(NSInteger currentIndex) {
        if ([weakSelf.cycleImages[currentIndex].is_links isEqualToString:@"0"]) {
            return ;
        }
        JQFYBannerViewController *banner = [JQFYBannerViewController new];
        WKWebView *webView = [[WKWebView alloc] initWithFrame:banner.view.bounds];
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:weakSelf.cycleImages[currentIndex].links]]];
        [banner.view addSubview:webView];
        [weakSelf.navigationController pushViewController:banner animated:YES];
    };
    self.homeList.tableHeaderView = self.scr;
}


#pragma mark - 跳转播放器界面 -
-(void)tapRhythmView{
    
    if (__Player__.playingSong == nil) {
        UIImageView *alertError = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"前往音乐（合并）"]];
        alertError.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
        [alertError addGestureRecognizer:tap];
        
        self.alert = [[ZJAnimationPopView alloc] initWithCustomView:alertError popStyle:ZJAnimationPopStyleScale dismissStyle:ZJAnimationDismissStyleScale];
        self.alert.popBGAlpha = 0.6;
        self.alert.isClickBGDismiss = YES;
        [self.alert pop];
        return;
    }
    //播放界面
    JQFYPlayViewController *playerVc = [[JQFYPlayViewController alloc] init];
    [self presentViewController:playerVc animated:YES completion:nil];
    
}

- (void)tap{
    [self.alert dismiss];
}


- (NSMutableArray *)images
{
    if (_images == nil) {
        _images = [NSMutableArray new];
        for (int i = 19; i < 24; i++) {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"图层%zd",i]];
            [_images addObject:image];
        }
    }
    return _images;
}

@end
